package cookie;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 浏览器发送请求带入Cookie，服务器端读取Cookie
 */
public class C2_ReadCookie extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("ReadCookie被调用...");

        //1.通过request对象获取所有Cookie
        Cookie[] cookies = req.getCookies();
        if (cookies != null) {
            System.out.println("======读取到的Cookie信息如下======");
            for (Cookie cookie : cookies) {
                System.out.println(cookie.getName() + " : " + cookie.getValue());
            }
        } else {
            System.out.println("没有读取到Cookie信息");
        }

        //2.给浏览器返回综合信息
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.println("<h1>读取cookie成功</h1>");
        out.flush();
        out.close();

    }
}
